package com.gooluke.localcache.config;

import com.gooluke.localcache.aop.LocalCacheAspect;
import com.gooluke.localcache.aop.LocalCacheEvictAspect;
import com.gooluke.localcache.cache.LocalCacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class LocalCacheConfig implements ApplicationRunner, DisposableBean {

    private static final Logger log = LoggerFactory.getLogger(LocalCacheConfig.class);

    private final LocalCacheManager localCacheManager = new LocalCacheManager();

    private final ScheduledExecutorService CACHE_CLEANUP_SCHEDULER = Executors.newScheduledThreadPool(1);

    @Value("${cache.cleanup.initialDelay:0}")
    private long initialDelay;

    @Value("${cache.cleanup.period:60}")
    private long period;


    @Bean
    public LocalCacheAspect localCacheAspect() {
        return new LocalCacheAspect(this.localCacheManager);
    }

    @Bean
    public LocalCacheEvictAspect localCacheEvictAspect() {
        return new LocalCacheEvictAspect(this.localCacheManager);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("CACHE_CLEANUP_SCHEDULER task initialDelay:{},period:{}", initialDelay, period);
        CACHE_CLEANUP_SCHEDULER.scheduleAtFixedRate(localCacheManager::cleanupExpired, initialDelay, period, TimeUnit.SECONDS);
    }

    @Override
    public void destroy() throws Exception {
        log.info("关闭CACHE_CLEANUP_SCHEDULER");
        CACHE_CLEANUP_SCHEDULER.shutdown();
    }
}